package com.gm.wholesale.module.order.ui.needOrder;

import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseListFragment;
import com.gm.commonlib.module.evenbus.EventBusUtils;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.wholesale.R;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.order.api.IOrderApi;
import com.gm.wholesale.module.order.bean.OrderBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean;
import com.gm.wholesale.module.order.interfaces.ISearchOrderByTime;
import com.gm.wholesale.module.order.model.NeedOrderModel;
import com.gm.wholesale.module.order.orderStatus.NeedOrderStatusType;
import com.gm.wholesale.module.order.ui.OrderMangerFragment;

import java.util.Date;
import java.util.List;

import io.reactivex.Observable;

public class NeedOrderListFragment extends BaseListFragment<NeedOrderBean, BasePageData<NeedOrderBean>> implements ISearchOrderByTime {

    private String mOrderingTimeBegin;
    private String mOrderingTimeEnd;

    private OrderMangerFragment mOrderMangerFragment;
    public void updateView(){
        mOrderingTimeBegin=null;
        refreshData();
    }
    @Override
    public void initPullToRefreshListView() {
        super.initPullToRefreshListView();
        mIsShowToast = false;
        setBodybg(getResources().getColor(R.color.white));
        pullToRefreshListView.setDivider(getResources().getDrawable(R.drawable.list_driver_shap));

    }



    public void setOrderMangerFragment(OrderMangerFragment orderMangerFragment) {
        mOrderMangerFragment = orderMangerFragment;
    }


    @Override
    protected void getDataFinish(List<NeedOrderBean> mDatas) {
        if (mDatas != null && !mDatas.isEmpty()) {
            mDatas.get(0).setClick(true);
            showOrderDetail(mDatas.get(0));
        } else {
            if (mOrderMangerFragment!=null){
                mOrderMangerFragment.hidNeedOrderDetailView();
            }
        }
    }

    @Override
    protected BaseAdapter createTempBaseAdapter() {
        return new CommonAdapter<>(getActivity(), mDatas, R.layout.list_need_order_item) {
            @Override
            public void convert(ViewHolder viewHolder, final NeedOrderBean data) {
                if (data.isChanged()) {
                    viewHolder.getView(R.id.hasUpdateTv).setVisibility(View.VISIBLE);
                } else {
                    viewHolder.getView(R.id.hasUpdateTv).setVisibility(View.GONE);
                }
                if (data.isClick()) {
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.color_e4f4eb));
                } else {
                    viewHolder.getConvertView().setBackgroundColor(mContext.getResources().getColor(R.color.white));
                }
                viewHolder.setText(R.id.orderNameTv, data.getCustomerName());
                viewHolder.setText(R.id.orderNumTv, data.getNeedsNo());
                viewHolder.setText(R.id.createTimeTv, data.getCreateTime());
                TextView orderStateTv = viewHolder.getView(R.id.orderStateTv);
                TextView redNtTv = viewHolder.getView(R.id.redNtTv);
                showOrderState(data, orderStateTv, redNtTv);
                viewHolder.getConvertView().setOnClickListener(v -> {
                    setDataClick(data);
                    showOrderDetail(data);
                });
            }
        };

    }

    private void showOrderState(NeedOrderBean data, TextView textView, TextView redNtTv) {
        if (data.getStatus() == NeedOrderStatusType.DJD.getType()) {
            textView.setText("未打印");
            textView.setTextColor(context.getResources().getColor(R.color.color_FF4D4F));
            redNtTv.setVisibility(View.VISIBLE);
        } else if (data.getStatus() == NeedOrderStatusType.YJD.getType()) {
            textView.setText("已打印");
            textView.setTextColor(context.getResources().getColor(R.color.color_06AE56));
            redNtTv.setVisibility(View.GONE);
        } else {
            textView.setText("已回执");
            textView.setTextColor(context.getResources().getColor(R.color.color_06AE56));
            redNtTv.setVisibility(View.GONE);
        }
    }


    private void showOrderDetail(NeedOrderBean needOrderBean) {
        EvenBusUtil.showNeedOrderDetail(needOrderBean);
    }


    private void setDataClick(NeedOrderBean clickData) {
        for (NeedOrderBean data : mDatas) {
            if (data.getNeedsId() == clickData.getNeedsId()) {
                data.setClick(true);
            } else {
                data.setClick(false);
            }
        }
        notifyListDataSetChanged();


    }


    @Override
    protected HttpServicesHolder<?, BasePageData<NeedOrderBean>> getHttpServicesHolder(long index) {
        return new HttpServicesHolder<IOrderApi, BasePageData<NeedOrderBean>>() {
            @Override
            public Observable<BasePageData<NeedOrderBean>> getHttpObservable(IOrderApi api) {
                ArrayMap<String, Object> quearyData = getArrayMap();
                quearyData.put("page", index);
                quearyData.put("pageSize", Constant.DEFAULTPAGESIZE);
                return api.getNeedOrderList(quearyData);
            }
        };
    }

    public void getUnReviceOrderSize() {
        NeedOrderModel.getUnReviceOrderSize(getArrayMap(), new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<Long> resp) {
                if (resp != null && mOrderMangerFragment != null) {
                    mOrderMangerFragment.showRedUnReviceOrderSize(resp.getData());
                }
            }

            @Override
            protected void onError(String error) {

            }
        });
    }

    public ArrayMap<String, Object> getArrayMap() {
        //订单类型，1-小程序现场单，2-小程序提前单，3-批发版现场单
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("type", 3);
        if (TextUtils.isEmpty(mOrderingTimeBegin)) {
            mOrderingTimeBegin = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
            mOrderingTimeEnd = mOrderingTimeBegin + " 23:59:59";
            mOrderingTimeBegin = mOrderingTimeBegin + " 00:00:00";
        }
        queryData.put("createTimeStart", mOrderingTimeBegin);
        queryData.put("createTimeEnd", mOrderingTimeEnd);


        return queryData;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        getUnReviceOrderSize();
        int code = event.getCode();
        //修改状态未已打印
        if (code == EventBusType.UPDATE_NEED_ORDER_LIST_ITEM.getType()
                || code == EventBusType.UPDATE_NEED_ORDER_DETAIL.getType()) {
            updateItemView((NeedOrderBean) event.getData());
        }

    }

    public void updateItemView(NeedOrderBean needOrderBean) {
        for (NeedOrderBean orderBean : mDatas) {
            if (needOrderBean.getNeedsId() == orderBean.getNeedsId()) {
                orderBean.setStatus(needOrderBean.getStatus());
                orderBean.setChanged(needOrderBean.isChanged());
                notifyListDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void searchOrderByTime(String begTime, String endTime) {
        mOrderingTimeBegin = begTime;
        mOrderingTimeEnd = endTime;
        getUnReviceOrderSize();
        refreshData();

    }

    public String getTime() {
        if (mOrderingTimeBegin == null) return null;
        Date date = DateTimeUtils.formatDateTime(mOrderingTimeBegin, DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
        return DateTimeUtils.formatDateTime(date, DateTimeUtils.HMD2);
    }


}
